import { onMounted, onUnmounted } from 'vue'

/**
 * 滚动显示动画 Composable
 * 使用 Intersection Observer API 实现元素进入视口时的动画效果
 */
export function useScrollReveal(options = {}) {
  const {
    threshold = 0.1,
    rootMargin = '0px',
    animationClass = 'reveal-active',
    once = true
  } = options

  let observer = null

  const initObserver = () => {
    observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add(animationClass)
          
          // 如果只触发一次，观察后取消观察
          if (once) {
            observer.unobserve(entry.target)
          }
        } else if (!once) {
          entry.target.classList.remove(animationClass)
        }
      })
    }, {
      threshold,
      rootMargin
    })
  }

  const observe = (elements) => {
    if (!observer) {
      initObserver()
    }

    if (elements instanceof NodeList || Array.isArray(elements)) {
      elements.forEach(el => observer.observe(el))
    } else if (elements instanceof Element) {
      observer.observe(elements)
    }
  }

  const unobserve = (elements) => {
    if (!observer) return

    if (elements instanceof NodeList || Array.isArray(elements)) {
      elements.forEach(el => observer.unobserve(el))
    } else if (elements instanceof Element) {
      observer.unobserve(elements)
    }
  }

  const disconnect = () => {
    if (observer) {
      observer.disconnect()
      observer = null
    }
  }

  onUnmounted(() => {
    disconnect()
  })

  return {
    observe,
    unobserve,
    disconnect
  }
}

/**
 * 自动观察带有指定属性的元素
 */
export function useAutoScrollReveal(selector = '[data-reveal]', options = {}) {
  const { observe, disconnect } = useScrollReveal(options)

  onMounted(() => {
    const elements = document.querySelectorAll(selector)
    if (elements.length > 0) {
      observe(elements)
    }
  })

  onUnmounted(() => {
    disconnect()
  })

  return {
    observe,
    disconnect
  }
}

